//
//  LoginView.m
//  pa
//
//  Created by HaiJiao Chen on 12-7-21.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "LoginView.h"
#import "FilePack.h"
#import "LoginServer.h"
#import "ASIFormDataRequest.h"
#import "XMLObject.h"
#import "AppDelegate.h"
#import "CHJAlertView.h"
#import "nibLoader.h"
#import "ServerView.h"
#include "text_def.h"
#include "CMD5.h"

NSString *const LoginSuccessfull = @"LoginSuccessfull";

#define MAX_TRY_LOGIN_SERVER 5

@implementation LoginView

- (void)initlize
{
    normalQuene = [[ASINetworkQueue alloc] init];
    [normalQuene setDelegate:self];
    [normalQuene setRequestDidFinishSelector:@selector(requestFinished:)];
    [normalQuene setRequestDidFailSelector:@selector(requestFailed:)];
    normalQuene.shouldCancelAllRequestsOnFailure = NO;
    [normalQuene go];
    loginServers = [[NSMutableArray alloc] initWithCapacity:10];
    tryServers = [[NSMutableArray alloc] initWithCapacity:10];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self initlize];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [self initlize];
    }
    return self;
}

- (void)dealloc
{
    [normalQuene cancelAllOperations];
    [normalQuene setDelegate:nil];
    [normalQuene release];
    [loginServers release];
    [tryServers release];
    [waittingView close];
    [super dealloc];
}


@synthesize user_name;
@synthesize truck_id;
@synthesize password;

- (IBAction)login:(id)sender
{
    if ([user_name.text length] == 0)
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:[FilePack getStringByID:STR_NEED_USER_NAME] message:nil delegate:nil cancelButtonTitle:[FilePack getStringByID:STR_OK] otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    else if ([truck_id.text length] == 0)
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:[FilePack getStringByID:STR_NEED_TRUCK_ID] message:nil delegate:nil cancelButtonTitle:[FilePack getStringByID:STR_OK] otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    else if ([password.text length] == 0)
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:[FilePack getStringByID:STR_NEED_PASSWORD] message:nil delegate:nil cancelButtonTitle:[FilePack getStringByID:STR_OK] otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    else
    {
        NSString* name = user_name.text;
        NSString* number = truck_id.text;
        NSString* pass = password.text;
        const char* c_pass = [password.text UTF8String];
        char buffer[128];
        md5_encode_str(buffer, c_pass);
        pass = [NSString stringWithUTF8String:buffer];
        
        md5_encode_bin((kx_u8*)buffer, (const kx_u8*)c_pass, strlen(c_pass));
        NSData* bytes_pass = [NSData dataWithBytes:buffer length:16];
        
        NSMutableDictionary* body = [NSMutableDictionary dictionaryWithCapacity:10];
        [body setValue:name forKey:@"uName"];
        [body setValue:number forKey:@"tNumber"];
        [body setValue:bytes_pass forKey:@"pWord"];
        [[AppDelegate sharedInstance] postHttpRequest:@"/Login" body:body params:[NSMutableDictionary dictionaryWithObject:number forKey:@"truckID"] delegate:self multipart:NO];
        
//        NSArray* servers = [LoginServer sharedInstance].data;
//        NSString* name = user_name.text;
//        NSString* number = truck_id.text;
//        NSString* pass = password.text;
//        char buffer[128];
//        md5_encode_str(buffer, [pass UTF8String]);
//        pass = [NSString stringWithUTF8String:buffer];
//        
//        [loginServers removeAllObjects];
//        //for (NSDictionary* dic in servers)
//        {
//            NSString* host = SERVER_URL;//[dic valueForKey:@"url"];
//            NSString* api = [NSString stringWithFormat:@"%@/Login", host];
//            
//            NSURL *url = [NSURL URLWithString:api];
//            ASIFormDataRequest* request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
//            
//            [request addPostValue:name forKey:@"uName"];
//            [request addPostValue:number forKey:@"tNumber"];
//            [request addPostValue:password.text forKey:@"pWord"];
//            [request addPostValue:[FilePack currentlanguage] forKey:@"Language"];
//            
//            request.postFormat = ASIURLEncodedPostFormat;
//            request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:host, @"url", nil];
//            request.timeOutSeconds = 20;
//            
//            [loginServers addObject:request];
//        }
//        
//        for (ASIFormDataRequest* request in tryServers)
//        {
//            [request cancel];
//        }
//        [tryServers removeAllObjects];
//    
//        int count = MAX_TRY_LOGIN_SERVER;
//        while (count > 0 && [loginServers count] > 0)
//        {
//            ASIFormDataRequest* request = [loginServers objectAtIndex:0];
//            [tryServers addObject:request];
//            [loginServers removeObjectAtIndex:0];
//            count--;
//        }
//        
//        for (ASIFormDataRequest* request in tryServers)
//        {
//            [normalQuene addOperation:request];
//        }
        
        waittingView = [[CHJAlertView alloc] init];
        [waittingView setLoadingText:[FilePack getStringByID:STR_PLEASE_WAIT] animated:YES];
        [waittingView show];
    }
}

- (IBAction)server:(id)sender
{
    ServerView* v = [nibLoader load:@"Servers" params:nil];
    [self addSubview:v];
    [v bind];
}

//- (void)requestFinished:(ASIHTTPRequest *)request
//{
//    XMLObject* xml = [XMLObject parse:[request rawResponseData]];
//    if ([xml getIntForKey:@"ret" defaultValue:0] == 1)
//    {
//        for (ASIFormDataRequest* request in tryServers)
//        {
//            [request cancel];
//        }
//        [tryServers removeAllObjects];
//        [loginServers removeAllObjects];
//        [normalQuene cancelAllOperations];
//        [[AppDelegate sharedInstance] setHost:[request.userInfo valueForKey:@"url"]];
//        [[AppDelegate sharedInstance] setToken:[xml getStringForKey:@"token" defaultValue:@""]];
//        [[AppDelegate sharedInstance] setUid:[xml getStringForKey:@"uid" defaultValue:@""]];
//        [waittingView close];
//        waittingView = nil;
//        [[NSNotificationCenter defaultCenter] postNotificationName:LoginSuccessfull object:nil];
//        [self removeFromSuperview];
//    }
//    else
//    {
//        [tryServers removeObject:request];
//        if ([tryServers count] == 0)
//        {
//            [waittingView setTitle:[FilePack getStringByID:STR_ERROR_OCCUR] max_width:160 animated:YES];
//            [waittingView closeInTime:2];
//            waittingView = nil;
//        }
//    }
//}
//
//- (void)requestFailed:(ASIHTTPRequest *)request
//{
//    [tryServers removeObject:request];
//    if ([loginServers count] > 0)
//    {
//        request = [loginServers objectAtIndex:0];
//        [tryServers addObject:request];
//        [loginServers removeObjectAtIndex:0];
//        [normalQuene addOperation:request];
//    }
//    else if ([tryServers count] == 0)
//    {
//        [waittingView setTitle:[FilePack getStringByID:STR_ERROR_OCCUR] max_width:160 animated:YES];
//        [waittingView closeInTime:2];
//        waittingView = nil;
//    }
//}

-(void)requestFinished:(NSMutableDictionary*)params data:(XMLObject*)data succ:(BOOL)succ
{
    if (succ)
    {
        if ([data getIntForKey:@"ret" defaultValue:0] != 1)
        {
            succ = NO;
        }
    }
    if (succ)
    {
        [[AppDelegate sharedInstance] setToken:[data getStringForKey:@"token" defaultValue:@""]];
        [[AppDelegate sharedInstance] setUid:[data getStringForKey:@"uid" defaultValue:@""]];
        [[AppDelegate sharedInstance] setTruckID:[params valueForKey:@"truckID"]];
        [waittingView close];
        waittingView = nil;
        [[NSNotificationCenter defaultCenter] postNotificationName:LoginSuccessfull object:nil];
        [self removeFromSuperview];
    }
    else
    {
        [waittingView setTitle:[data getStringForKey:@"error" defaultValue:[FilePack getStringByID:STR_ERROR_OCCUR]]  max_width:160 animated:YES];
        [waittingView closeInTime:2];
        waittingView = nil;
    }
}

@end
